package cn.edu.seu.ssny.service.impl;

import cn.edu.seu.ssny.dao.IDeviceCategoryDao;
import cn.edu.seu.ssny.dao.support.IBaseDao;
import cn.edu.seu.ssny.entity.Device;
import cn.edu.seu.ssny.entity.DeviceCategory;
import cn.edu.seu.ssny.entity.Project;
import cn.edu.seu.ssny.service.IDeviceCategoryService;
import cn.edu.seu.ssny.service.IDeviceService;
import cn.edu.seu.ssny.service.support.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.expression.spel.ast.OpAnd;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 设备数据表
 */
@Service
public class DeviceCategoryServiceImpl extends BaseServiceImpl<DeviceCategory, Integer> implements IDeviceCategoryService {

    @Autowired
    private IDeviceCategoryDao deviceCategoryDao;

    @Autowired
    private IDeviceService deviceService;

    @Override
    public IBaseDao<DeviceCategory, Integer> getBaseDao() {
        return this.deviceCategoryDao;
    }

    @Override
    public List<DeviceCategory> findByProject(Project project) {
        return deviceCategoryDao.findByProjectOrderByName(project);
    }

    @Override
    public DeviceCategory findByProjectAndName(Project project, String name) {
        Optional<DeviceCategory> categoryOptional = deviceCategoryDao.findByProjectAndName(project, name);
        DeviceCategory category = null;
        if(categoryOptional.isPresent())
            category = categoryOptional.get();
        else
            category = new DeviceCategory();
            category.setName(name);
            category = saveAndFlush(category, project);
        return category;
    }

//    @Override
//    public void updateDevices(DeviceCategory category, int deviceId) {
//        Device device = deviceService.find(deviceId);
//        List<Device> devices = category.getDevices();
//
//        System.out.println("===device-size "+devices.size());
//        for(Device d: category.getDevices()){
//            System.out.println(d.getName());
//        }
//
//        if(device == null || !devices.contains(device))
//            return;
//        devices.remove(device);
//        System.out.println("===device-size "+devices.size());
//        for(Device d: category.getDevices()){
//            System.out.println(d.getName());
//        }
//        category.setDevices(devices);
//        update(category);
//        System.out.println("===1device-size "+category.getDevices().size());
//        for(Device d: category.getDevices()){
//            System.out.println(d.getName());
//        }
//    }

    @Override
    public DeviceCategory saveAndFlush(DeviceCategory category, Project project) {
        category.setProject(project);
        return saveAndFlush(category);
    }
}